<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="baidu-site-verification" content="code-Vc9hmj7JE9" />
<meta name="google-site-verification" content="tMVEtTlHbEdIEga44DZi47Yu8Pl2shFKVZcqz6rfSW0" />
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://kun-bin.github.io/");
                } else {
                    history.back();
                }
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="/css/matery.css">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python,sklearn,keras,lstm,回归," />










<meta name="description" content="因为接到了股票价格预测的任务，所以开始研究怎么写代码。实际上代码是网上现成的，并不需要自己研究算法和网络结构，复制粘贴再重新组合一下就好，所以难度不大。之前做过sklearn的分类问题，现在做回归，思路是差不多的。">
<meta property="og:type" content="article">
<meta property="og:title" content="python+sklearn+keras+lstm回归预测问题">
<meta property="og:url" content="https://likun1208.github.io/2020/07/24/python-sklearn-keras-lstm%E5%9B%9E%E5%BD%92%E9%A2%84%E6%B5%8B%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="左边">
<meta property="og:description" content="因为接到了股票价格预测的任务，所以开始研究怎么写代码。实际上代码是网上现成的，并不需要自己研究算法和网络结构，复制粘贴再重新组合一下就好，所以难度不大。之前做过sklearn的分类问题，现在做回归，思路是差不多的。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-07-23T23:38:36.000Z">
<meta property="article:modified_time" content="2020-12-21T06:31:24.686Z">
<meta property="article:author" content="Kun Li">
<meta property="article:tag" content="python">
<meta property="article:tag" content="sklearn">
<meta property="article:tag" content="keras">
<meta property="article:tag" content="lstm">
<meta property="article:tag" content="回归">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://likun1208.github.io/2020/07/24/python-sklearn-keras-lstm回归预测问题/"/>





  <title>python+sklearn+keras+lstm回归预测问题 | 左边</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">左边</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>
	<script type="text/javascript" src="/js/echarts.min.js"></script>
    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://likun1208.github.io/2020/07/24/python-sklearn-keras-lstm%E5%9B%9E%E5%BD%92%E9%A2%84%E6%B5%8B%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Kun Li">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="左边">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python+sklearn+keras+lstm回归预测问题</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-07-24T07:38:36+08:00">
                2020-07-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%97%A0%E5%88%86%E7%B1%BB%E9%A1%B9/" itemprop="url" rel="index">
                    <span itemprop="name">无分类项</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>因为接到了股票价格预测的任务，所以开始研究怎么写代码。实际上代码是网上现成的，并不需要自己研究算法和网络结构，复制粘贴再重新组合一下就好，所以难度不大。之前做过sklearn的分类问题，现在做回归，思路是差不多的。</p>
<a id="more"></a>
<p>具体场景是：给定某时间段内的股票价格数据，预测接下来的走势；用同样的算法预测其他股票，看准确率是否有变化；老师的想法是对比国内外市场的差异，看是否在机器学习算法中也有体现。</p>
<h2 id="导入包"><a href="#导入包" class="headerlink" title="导入包"></a>导入包</h2><p>这里先列一下所有导入的包，可能有一些实际没用上：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> math</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> matplotlib <span class="keyword">import</span> style</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> preprocessing, svm</span><br><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LinearRegression</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> train_test_split</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime <span class="keyword">as</span> date</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> tree</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> linear_model</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> svm</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> neighbors</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> ensemble</span><br><span class="line"><span class="keyword">from</span> sklearn.ensemble <span class="keyword">import</span> BaggingRegressor</span><br><span class="line"><span class="keyword">from</span> sklearn.tree <span class="keyword">import</span> ExtraTreeRegressor</span><br><span class="line"><span class="keyword">from</span> sklearn.model_selection <span class="keyword">import</span> cross_val_score</span><br><span class="line"><span class="keyword">import</span> quandl</span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> metrics</span><br><span class="line"><span class="comment">#from pandas_datareader import data</span></span><br><span class="line"><span class="keyword">import</span> yfinance <span class="keyword">as</span> yf</span><br><span class="line"><span class="comment"># 下面这几个是lstm用的</span></span><br><span class="line"><span class="keyword">from</span> sklearn.preprocessing <span class="keyword">import</span> MinMaxScaler</span><br><span class="line"><span class="keyword">from</span> tensorflow.keras.models <span class="keyword">import</span> Sequential</span><br><span class="line"><span class="keyword">from</span> tensorflow.keras.layers <span class="keyword">import</span> Dense, Dropout, LSTM</span><br></pre></td></tr></table></figure>
<h2 id="数据获取"><a href="#数据获取" class="headerlink" title="数据获取"></a>数据获取</h2><ol>
<li><p>使用quandl获取数据：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> quandl</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line">start = date(<span class="number">2000</span>,<span class="number">1</span>,<span class="number">1</span>)</span><br><span class="line">end = date.today()</span><br><span class="line">quandl.ApiConfig.api_key = <span class="string">"gEyzpvmpXReFE8Z8TEps"</span></span><br><span class="line">stock_df = pd.DataFrame(quandl.get(<span class="string">"WIKI/GOOGL"</span>, start_date=start, end_date=end))</span><br></pre></td></tr></table></figure>
<p>第一行导入包；</p>
<p>第二行第三行设置要获取的数据时间范围</p>
<p>第四行设置api_key，这里是需要到quandl官网注册账户，注册好以后会得到这个key，可以用免费数据。注册的时候分为3步，填名字邮箱密码啥的，第三步的时候会需要点一个人机验证的东西才能注册成功，如果没出现人机验证且无法点注册的按钮，说明需要翻墙。</p>
<p>第五行通过<code>quandl.get()</code>函数可以得到所需数据，转成<code>pandas</code>格式方便后续分析。这里的<code>WIKI/GOOGL</code>是谷歌的股票数据在quandl网站上的代码，不过我看不懂那个网站，不清楚要怎么找其他公司和时间的数据，所以暂时就先只用这个了。</p>
</li>
<li><p>通过tushare和pandas_datareader这两个模块也可以获取数据，此外还有其他相关网站。</p>
</li>
<li><p>发现pandas_datareader实际上不太行，查了一下找到了新的数据，数据来源是雅虎财经：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> yfinance <span class="keyword">as</span> yf</span><br><span class="line">start_date = <span class="string">"2000-01-01"</span></span><br><span class="line">end_date = <span class="string">"2018-12-01"</span></span><br><span class="line">stock_df = yf.download(tickers = <span class="string">"MCD"</span>, start = start_date, end = end_date)</span><br></pre></td></tr></table></figure>
<p>这里<code>start_date</code>和<code>end_date</code>也可以写成前面<code>date(2000,1,1)</code>的样子，<code>tickers</code>的参数是可以百度到的股票代码，如果是上海的就是<code>600673.SS</code>这种代码后面加<code>.SS</code>，深圳是<code>.SZ</code>，香港是<code>.HK</code>，美国就是那串字母本身，此外，香港的代码查到的都是五位数，但是在这里要把最高位的0去掉，只用四位数。</p>
<p><code>yf.download</code>会直接返回<code>pandas</code>的<code>dataframe</code>结构，方便后续处理。</p>
<p>和前面那个<code>quandl</code>的比起来，简单了很多，但是有时候会运行很慢，等十几分钟也不出结果。</p>
</li>
</ol>
<h2 id="sklearn的普通方法"><a href="#sklearn的普通方法" class="headerlink" title="sklearn的普通方法"></a>sklearn的普通方法</h2><ol>
<li><p>把预测要用的数据列提取出来</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">stock_df = stock_df[[<span class="string">'Open'</span>, <span class="string">'High'</span>, <span class="string">'Low'</span>, <span class="string">'Close'</span>, <span class="string">'Volume'</span>]]</span><br></pre></td></tr></table></figure>
</li>
<li><p>这里使用过去一天的数据来预测当天的收盘价，因此要新建一列来存下一天的收盘价作为机器学习的目标值<code>y</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">stock_df[<span class="string">'object'</span>] = stock_df[<span class="string">'Close'</span>].shift(<span class="number">-1</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>把除了目标列以外的其他数据单独提出来作为<code>X</code>，并做标准化处理，然后去掉最后一行（因为最后一行没有下一天的目标值，所以没法用）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">X = np.array(stock_df.drop([<span class="string">'object'</span>], <span class="number">1</span>))</span><br><span class="line">X = preprocessing.scale(X)</span><br><span class="line">X = X[:<span class="number">-1</span>]</span><br></pre></td></tr></table></figure>
</li>
<li><p>把目标列提出来作为<code>y</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">stock_df.dropna(inplace=<span class="literal">True</span>)</span><br><span class="line">y = np.array(stock_df[<span class="string">'object'</span>])</span><br></pre></td></tr></table></figure>
</li>
<li><p>划分训练集和测试集</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=<span class="number">0.3</span>, random_state=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>把要用的模型都准备好</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">models = []</span><br><span class="line">models.append((<span class="string">'DecisionTree'</span>, tree.DecisionTreeRegressor()))</span><br><span class="line">models.append((<span class="string">'LR'</span>, linear_model.LinearRegression()))</span><br><span class="line">models.append((<span class="string">'KNN'</span>, neighbors.KNeighborsRegressor()))</span><br><span class="line">models.append((<span class="string">'RF'</span>, ensemble.RandomForestRegressor(n_estimators=<span class="number">20</span>)))</span><br><span class="line">models.append((<span class="string">'ABR'</span>, ensemble.AdaBoostRegressor(n_estimators=<span class="number">50</span>)))</span><br><span class="line">models.append((<span class="string">'SVM'</span>, svm.SVR(gamma=<span class="string">'auto'</span>)))</span><br><span class="line">models.append((<span class="string">'GBRT'</span>, ensemble.GradientBoostingRegressor(n_estimators=<span class="number">100</span>)))</span><br><span class="line">models.append((<span class="string">'Bagging'</span>, BaggingRegressor()))</span><br><span class="line">models.append((<span class="string">'ExtraTree'</span>, ExtraTreeRegressor()))</span><br></pre></td></tr></table></figure>
</li>
<li><p>遍历所有模型，在训练集上10折交叉验证并输出模型评价，在测试集上计算均方根误差</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> name, model <span class="keyword">in</span> models:</span><br><span class="line">    scores = cross_val_score(model, x_train, y_train, cv=<span class="number">10</span>, scoring=<span class="literal">None</span>)</span><br><span class="line">    print(<span class="string">'%s: %f (%f)'</span> % (name, scores.mean(), scores.std()))</span><br><span class="line">    model.fit(x_train, y_train)</span><br><span class="line">    <span class="comment">#print(model.score(x_test, y_test))</span></span><br><span class="line">    y_predict = model.predict(x_test)</span><br><span class="line">    print(<span class="string">'RMSE: '</span>, np.sqrt(metrics.mean_squared_error(y_test,y_predict)))</span><br></pre></td></tr></table></figure>
</li>
<li><p>接下来要随便选个模型画图看看</p>
<ol>
<li><p>选模型并用训练集训练模型</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">clf = ensemble.GradientBoostingRegressor(n_estimators=<span class="number">100</span>)</span><br><span class="line">clf.fit(x_train, y_train)</span><br></pre></td></tr></table></figure>
</li>
<li><p>从所有的X中，选取后30%，用模型预测结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">index = len(X)*<span class="number">7</span>//<span class="number">10</span></span><br><span class="line">predict_x = X[index:]</span><br><span class="line">predict_y = clf.predict(predict_x)</span><br></pre></td></tr></table></figure>
</li>
<li><p>在原本的<code>dataframe</code>中新建一列来存这个预测结果，这样后面画图能直接用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">stock_df[<span class="string">'Predict'</span>] = np.nan			<span class="comment">#新建一列并初始化为空值</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> predict_y:						<span class="comment">#遍历预测结果</span></span><br><span class="line">    stock_df[<span class="string">'Predict'</span>][index] = i		<span class="comment">#从预测的第一个数开始填值</span></span><br><span class="line">    index += <span class="number">1</span>							<span class="comment">#移动到下一个值</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>画图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">plt.plot(stock_df[<span class="string">'Close'</span>], label=<span class="string">'Close'</span>, color=<span class="string">'deepskyblue'</span>)	<span class="comment">#实际值</span></span><br><span class="line">stock_df[<span class="string">'Predict'</span>].plot()										<span class="comment">#预测值</span></span><br><span class="line">plt.legend(loc=<span class="number">4</span>)</span><br><span class="line">plt.xlabel(<span class="string">'Date'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'Price'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
</li>
</ol>
</li>
</ol>
<h2 id="lstm"><a href="#lstm" class="headerlink" title="lstm"></a>lstm</h2><ol>
<li><p>预处理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">stock_df[<span class="string">'Date'</span>] = stock_df.index</span><br><span class="line">data = stock_df.sort_index(ascending=<span class="literal">True</span>, axis=<span class="number">0</span>)</span><br><span class="line">new_data = pd.DataFrame(index=range(<span class="number">0</span>, len(stock_df)), columns=[<span class="string">'Date'</span>, <span class="string">'Close'</span>])</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, len(data)):</span><br><span class="line">    new_data[<span class="string">'Date'</span>][i] = data[<span class="string">'Date'</span>][i]</span><br><span class="line">    new_data[<span class="string">'Close'</span>][i] = data[<span class="string">'Close'</span>][i]</span><br><span class="line"><span class="comment"># setting index</span></span><br><span class="line">new_data.index = new_data.Date</span><br><span class="line">new_data.drop(<span class="string">'Date'</span>, axis=<span class="number">1</span>, inplace=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure>
<p>这样的结果就是把日期和收盘价单独提出来了</p>
</li>
<li><p>划分训练集和测试集，是7:3划分</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">dataset = new_data.values</span><br><span class="line">t_len = len(dataset)*<span class="number">7</span>//<span class="number">10</span></span><br><span class="line">train = dataset[<span class="number">0</span>:t_len, :]</span><br><span class="line">valid = dataset[t_len:, :]</span><br></pre></td></tr></table></figure>
</li>
<li><p>处理训练集数据，lstm会利用过去一段时间的数据，这里设置为过去60天</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#标准化处理</span></span><br><span class="line">scaler = MinMaxScaler(feature_range=(<span class="number">0</span>, <span class="number">1</span>))</span><br><span class="line">scaled_data = scaler.fit_transform(dataset)</span><br><span class="line"><span class="comment">#定义列表存放数据</span></span><br><span class="line">x_train, y_train = [], []</span><br><span class="line"><span class="comment">#对于每一天的y，x的值都是过去60天的收盘价</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">60</span>, len(train)):</span><br><span class="line">    x_train.append(scaled_data[i - <span class="number">60</span>:i, <span class="number">0</span>])</span><br><span class="line">    y_train.append(scaled_data[i, <span class="number">0</span>])</span><br><span class="line"><span class="comment">#把x的格式改成训练需要的格式</span></span><br><span class="line">x_train, y_train = np.array(x_train), np.array(y_train)</span><br><span class="line">x_train = np.reshape(x_train, (x_train.shape[<span class="number">0</span>], x_train.shape[<span class="number">1</span>], <span class="number">1</span>))</span><br></pre></td></tr></table></figure>
</li>
<li><p>建立和训练lstm模型，这里训练50轮，实际上感觉100轮和50轮没什么差别；这里用了4层lstm，但实际上感觉一层就够了。在训练时用均方根误差作为指标。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># create and fit the LSTM network</span></span><br><span class="line">model = Sequential()</span><br><span class="line">model.add(LSTM(units=<span class="number">50</span>, return_sequences=<span class="literal">True</span>, input_shape=(x_train.shape[<span class="number">1</span>], <span class="number">1</span>)))</span><br><span class="line">model.add(Dropout(<span class="number">0.2</span>))</span><br><span class="line">model.add(LSTM(units = <span class="number">50</span>, return_sequences = <span class="literal">True</span>))</span><br><span class="line">model.add(Dropout(<span class="number">0.2</span>))</span><br><span class="line">model.add(LSTM(units = <span class="number">50</span>, return_sequences = <span class="literal">True</span>))</span><br><span class="line">model.add(Dropout(<span class="number">0.2</span>))</span><br><span class="line">model.add(LSTM(units=<span class="number">50</span>))</span><br><span class="line">model.add(Dropout(<span class="number">0.2</span>))</span><br><span class="line">model.add(Dense(<span class="number">1</span>))</span><br><span class="line">model.compile(loss=<span class="string">'mean_squared_error'</span>, optimizer=<span class="string">'adam'</span>)</span><br><span class="line">model.fit(x_train, y_train, epochs=<span class="number">50</span>, batch_size=<span class="number">32</span>, verbose=<span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<p>需要注意的是，这些lstm模型用的激活函数是默认的<code>tanh</code>，然后训练时会有错误信息，据一些人说是可以忽略的，参见<a href="https://github.com/tensorflow/tensorflow/issues/30263" target="_blank" rel="noopener">链接</a>。如果把激活函数改成<code>sigmoid</code>，就没报错了，但是发现训练结果格外不好，不清楚是我操作问题还是这个激活函数就不合适。总之暂且先用<code>tanh</code>。</p>
</li>
<li><p>准备测试集，这里和训练集一样，往前倒60个数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">inputs = new_data[len(new_data) - len(valid) - <span class="number">60</span>:].values</span><br><span class="line">inputs = inputs.reshape(<span class="number">-1</span>, <span class="number">1</span>)</span><br><span class="line">inputs = scaler.transform(inputs)</span><br><span class="line">X_test, Y_test = [], []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">60</span>, inputs.shape[<span class="number">0</span>]):</span><br><span class="line">    X_test.append(inputs[i - <span class="number">60</span>:i, <span class="number">0</span>])</span><br><span class="line">X_test = np.array(X_test)</span><br><span class="line">X_test = np.reshape(X_test, (X_test.shape[<span class="number">0</span>], X_test.shape[<span class="number">1</span>], <span class="number">1</span>))</span><br></pre></td></tr></table></figure>
</li>
<li><p>用训练好的lstm模型对测试集进行测试并把值改回标准化前的值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">closing_price = model.predict(X_test)</span><br><span class="line">closing_price = scaler.inverse_transform(closing_price)</span><br></pre></td></tr></table></figure>
</li>
<li><p>输出均方根误差</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rms &#x3D; np.sqrt(np.mean(np.power((valid - closing_price), 2)))</span><br><span class="line">print(rms)</span><br></pre></td></tr></table></figure>
</li>
<li><p>和sklearn一样的画图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">train = new_data[:t_len]</span><br><span class="line">valid = new_data[t_len:]</span><br><span class="line">valid[<span class="string">'Predictions'</span>] = closing_price</span><br><span class="line">plt.plot(train[<span class="string">'Adj. Close'</span>], color=<span class="string">'deepskyblue'</span>, label = <span class="string">'Adj. Close'</span>)</span><br><span class="line">plt.plot(valid[<span class="string">'Adj. Close'</span>], color=<span class="string">'deepskyblue'</span>)</span><br><span class="line">plt.plot(valid[<span class="string">'Predictions'</span>], label = <span class="string">'Predict'</span>)</span><br><span class="line">plt.legend(loc=<span class="number">4</span>)</span><br><span class="line">plt.xlabel(<span class="string">'Date'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'Price'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="其他说明"><a href="#其他说明" class="headerlink" title="其他说明"></a>其他说明</h2><ol>
<li>之后有空的时候再增加这些算法的理论介绍</li>
<li>回归和分类的代码结构差不多，只是函数名称和模型评价指标不太一样，关于评价指标可以参考<a href="https://scikit-learn.org/stable/modules/model_evaluation.html#the-scoring-parameter-defining-model-evaluation-rules" target="_blank" rel="noopener">这个</a>。</li>
</ol>

      
    </div>
    
    
    

    

    

    
	
	<div>
		
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
		
	</div>
	
    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
          
            <a href="/tags/sklearn/" rel="tag"><i class="fa fa-tag"></i> sklearn</a>
          
            <a href="/tags/keras/" rel="tag"><i class="fa fa-tag"></i> keras</a>
          
            <a href="/tags/lstm/" rel="tag"><i class="fa fa-tag"></i> lstm</a>
          
            <a href="/tags/%E5%9B%9E%E5%BD%92/" rel="tag"><i class="fa fa-tag"></i> 回归</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/18/%E8%AE%BA%E6%96%87%E8%AE%B0%E5%BD%95-N-in-One-A-Novel-Location-Based-Service/" rel="next" title="论文记录-N-in-One: A Novel Location-Based-Service">
                <i class="fa fa-chevron-left"></i> 论文记录-N-in-One: A Novel Location-Based-Service
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/08/11/blender%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95-3/" rel="prev" title="blender学习记录-3">
                blender学习记录-3 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="Kun Li" />
            
              <p class="site-author-name" itemprop="name">Kun Li</p>
              <p class="site-description motion-element" itemprop="description">三月樱，六月雪，也望尘莫及</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
				<a href="/archives/">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">27</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/likun1208" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="likun@mail.bnu.edu.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导入包"><span class="nav-number">1.</span> <span class="nav-text">导入包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据获取"><span class="nav-number">2.</span> <span class="nav-text">数据获取</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#sklearn的普通方法"><span class="nav-number">3.</span> <span class="nav-text">sklearn的普通方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lstm"><span class="nav-number">4.</span> <span class="nav-text">lstm</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他说明"><span class="nav-number">5.</span> <span class="nav-text">其他说明</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Kun Li</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('Success')
          else $(this).text('Fail')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('Copy')
        }, 300)
      }).append(e)
    })
  </script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/z16.model.json"},"display":{"position":"left","width":175,"height":350},"mobile":{"show":false},"log":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>
